<template>
  <div class="app-container">
    <div class="app-card">
      <!-- 搜索和工具栏 -->
      <div class="table-toolbar">
        <el-form :inline="true" :model="queryParams" ref="queryForm">
          <el-form-item label="订单编号">
            <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable size="small" />
          </el-form-item>
          <el-form-item label="团长">
            <el-select v-model="queryParams.leaderId" placeholder="请选择团长" clearable size="small">
              <el-option v-for="item in leaderOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
              <el-option :value="0" label="待处理" />
              <el-option :value="1" label="已处理" />
              <el-option :value="2" label="配送中" />
              <el-option :value="3" label="已完成" />
              <el-option :value="4" label="已取消" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              size="small"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        
        <div>
          <el-button type="warning" icon="el-icon-download" size="small" @click="handleExport">导出</el-button>
        </div>
      </div>
      
      <!-- 表格 -->
      <el-table v-loading="loading" :data="orderList" border>
        <el-table-column type="index" label="#" width="50" align="center" />
        <el-table-column prop="orderNo" label="订单编号" min-width="180" />
        <el-table-column prop="leaderName" label="团长" width="100" />
        <el-table-column prop="totalAmount" label="总金额" width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="280" align="center">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>
            <el-button 
              v-if="scope.row.status === 0" 
              type="text" 
              icon="el-icon-check" 
              @click="handleProcess(scope.row)">处理
            </el-button>
            <el-button 
              v-if="scope.row.status === 1" 
              type="text" 
              icon="el-icon-truck" 
              @click="handleDelivery(scope.row)">配送
            </el-button>
            <el-button 
              v-if="scope.row.status === 2" 
              type="text" 
              icon="el-icon-finished" 
              @click="handleComplete(scope.row)">完成
            </el-button>
            <el-button 
              v-if="scope.row.status < 3" 
              type="text" 
              icon="el-icon-close" 
              @click="handleCancel(scope.row)">取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.size"
          :current-page="queryParams.current"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" :visible.sync="detailVisible" width="800px" append-to-body>
      <div v-loading="detailLoading">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="订单编号">{{ orderDetail.order?.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ orderDetail.order?.createTime }}</el-descriptions-item>
          <el-descriptions-item label="团长">{{ orderDetail.leaderName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ orderDetail.leaderPhone }}</el-descriptions-item>
          <el-descriptions-item label="提货地址">{{ orderDetail.leaderAddress }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(orderDetail.order?.status)">{{ getStatusText(orderDetail.order?.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="总金额" :span="2">
            <span class="text-danger font-bold">¥{{ orderDetail.order?.totalAmount }}</span>
          </el-descriptions-item>
        </el-descriptions>
        
        <el-table :data="orderDetail.items" border style="margin-top: 20px;">
          <el-table-column type="index" label="#" width="50" align="center" />
          <el-table-column prop="productName" label="商品名称" min-width="200" />
          <el-table-column prop="productPrice" label="单价" width="100">
            <template slot-scope="scope">
              ¥{{ scope.row.productPrice }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column prop="subtotal" label="小计" width="120">
            <template slot-scope="scope">
              ¥{{ scope.row.subtotal }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrders, getOrder, updateOrderStatus, cancelOrder, exportOrders } from '@/api/order'
import { listLeaders } from '@/api/leader'

export default {
  name: 'Order',
  data() {
    return {
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        orderNo: '',
        leaderId: '',
        status: '',
        startTime: '',
        endTime: ''
      },
      // 日期范围
      dateRange: [],
      // 总记录数
      total: 0,
      // 订单列表
      orderList: [],
      // 团长选项
      leaderOptions: [],
      // 加载状态
      loading: false,
      // 订单详情对话框显示状态
      detailVisible: false,
      // 详情加载状态
      detailLoading: false,
      // 订单详情
      orderDetail: {
        order: {},
        items: [],
        leaderName: '',
        leaderPhone: '',
        leaderAddress: ''
      }
    }
  },
  created() {
    this.getList()
    this.getLeaderOptions()
  },
  methods: {
    // 获取订单列表
    getList() {
      this.loading = true
      
      // 处理时间范围
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.startTime = this.dateRange[0]
        this.queryParams.endTime = this.dateRange[1]
      } else {
        this.queryParams.startTime = ''
        this.queryParams.endTime = ''
      }
      
      listOrders(this.queryParams).then(response => {
        // 如果返回的是数组，直接使用
        if (Array.isArray(response)) {
          this.orderList = response
          this.total = response.length
        } else {
          // 否则尝试获取list和total字段
          this.orderList = response.list || response.records || []
          this.total = response.total || 0
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 获取团长选项
    getLeaderOptions() {
      listLeaders({ size: 100 }).then(response => {
        // 如果返回的是数组，直接使用
        if (Array.isArray(response)) {
          this.leaderOptions = response
        } else {
          this.leaderOptions = response.list || []
        }
      })
    },
    // 搜索按钮点击事件
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    // 重置按钮点击事件
    resetQuery() {
      this.dateRange = []
      this.$refs.queryForm.resetFields()
      this.queryParams.orderNo = ''
      this.queryParams.leaderId = ''
      this.queryParams.status = ''
      this.queryParams.startTime = ''
      this.queryParams.endTime = ''
      this.queryParams.current = 1
      this.getList()
    },
    // 每页数量改变事件
    handleSizeChange(val) {
      this.queryParams.size = val
      this.getList()
    },
    // 页码改变事件
    handleCurrentChange(val) {
      this.queryParams.current = val
      this.getList()
    },
    // 查看详情按钮点击事件
    handleDetail(row) {
      this.detailVisible = true
      this.detailLoading = true
      this.orderDetail = {
        order: {},
        items: [],
        leaderName: '',
        leaderPhone: '',
        leaderAddress: ''
      }
      
      getOrder(row.id).then(response => {
        this.orderDetail = response || {
          order: {},
          items: [],
          leaderName: '',
          leaderPhone: '',
          leaderAddress: ''
        }
        this.detailLoading = false
      }).catch(() => {
        this.detailLoading = false
      })
    },
    // 处理订单按钮点击事件
    handleProcess(row) {
      this.$confirm('确认处理该订单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateOrderStatus(row.id, 1).then(() => {
          this.$message.success('订单已处理')
          this.getList()
        })
      }).catch(() => {})
    },
    // 配送订单按钮点击事件
    handleDelivery(row) {
      this.$confirm('确认将该订单标记为配送中吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateOrderStatus(row.id, 2).then(() => {
          this.$message.success('订单已标记为配送中')
          this.getList()
        })
      }).catch(() => {})
    },
    // 完成订单按钮点击事件
    handleComplete(row) {
      this.$confirm('确认将该订单标记为已完成吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateOrderStatus(row.id, 3).then(() => {
          this.$message.success('订单已标记为已完成')
          this.getList()
        })
      }).catch(() => {})
    },
    // 取消订单按钮点击事件
    handleCancel(row) {
      this.$confirm('确认取消该订单吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelOrder(row.id).then(() => {
          this.$message.success('订单已取消')
          this.getList()
        })
      }).catch(() => {})
    },
    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case 0: return '待处理'
        case 1: return '已处理'
        case 2: return '配送中'
        case 3: return '已完成'
        case 4: return '已取消'
        default: return '未知'
      }
    },
    // 获取状态类型
    getStatusType(status) {
      switch (status) {
        case 0: return 'info'
        case 1: return 'primary'
        case 2: return 'warning'
        case 3: return 'success'
        case 4: return 'danger'
        default: return 'info'
      }
    },
    // 导出按钮点击事件
    handleExport() {
      const loadingInstance = this.$loading({
        lock: true,
        text: '正在导出订单数据，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      
      exportOrders().then(response => {
        loadingInstance.close()
        
        // 检查返回的数据是否是Blob类型
        if (!(response instanceof Blob)) {
          this.$message.error('导出失败：返回数据格式不正确')
          return
        }
        
        // 检查是否是错误消息（JSON格式）
        if (response.type === 'application/json') {
          // 读取JSON错误消息
          const reader = new FileReader()
          reader.onload = () => {
            try {
              const errorData = JSON.parse(reader.result)
              this.$message.error(errorData.message || '导出失败')
            } catch (e) {
              this.$message.error('导出失败：未知错误')
            }
          }
          reader.readAsText(response)
          return
        }
        
        // 创建Blob对象
        const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        
        // 创建下载链接
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = '订单列表.xlsx'
        
        // 触发点击事件下载文件
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        
        this.$message({
          message: '导出成功',
          type: 'success'
        })
      }).catch(error => {
        loadingInstance.close()
        console.error('导出失败:', error)
        this.$message({
          message: '导出失败：' + (error.message || '未知错误'),
          type: 'error'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.table-toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.text-danger {
  color: #F56C6C;
}

.font-bold {
  font-weight: bold;
}
</style> 